package com.scpii.api.controller.content;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.scpii.api.common.annoation.Pagination;
import com.scpii.api.common.base.BaseController;
import com.scpii.api.domain.content.Comments;
import com.scpii.api.service.content.CommentsService;
import com.scpii.api.util.FileUtil;
import com.scpii.api.util.PrincipalUtil;

@Controller
@RequestMapping("/content/comments")
public class CommentsController extends BaseController {

	@Resource
	private CommentsService commentsService;

	@PreAuthorize("hasRole('ROLE_USER')")
	@RequestMapping(value = "/user", method = RequestMethod.POST)
	@ResponseBody
	public Boolean addUserComments(
			@RequestParam("targetId") Long targetId,
			@RequestParam("parentId") Long parentId,
			@RequestParam("content") String content,
			@RequestParam(value = "commentType", required = false, defaultValue = "0") Integer commentType,
			@RequestParam(value = "files", required = false) MultipartFile[] files,
			Comments comments) {
		comments.setCreateBy(PrincipalUtil.getPrincipal().getId());
		comments.setAppId(PrincipalUtil.getPrincipal().getAppId());
		comments.setCommentType(commentType);
		comments.setCreateDt(new Date());
		comments.setParentId(parentId);
		comments.setTargetId(targetId);
		comments.setContent(content);
		comments.setResources(FileUtil.save(files, comments.getContent()));
		commentsService.insertComments(comments);
		return true;
	}

	@PreAuthorize("hasRole('ROLE_CLIENT')")
	@RequestMapping(value = "/target/{targetId}", method = RequestMethod.GET)
	@ResponseBody
	@Pagination
	public List<Comments> getCommentsByTargetId(
			@PathVariable("targetId") Long targetId, Comments comments) {
		comments.setTargetId(targetId);
		return commentsService.selectBySelective(comments);
	}

}
